package com.me.components {
	import flash.events.MouseEvent;

	import mx.core.FlexGlobals;

	import spark.core.SpriteVisualElement;

	/**
	 *
	 * @author yw
	 *
	 * @Date 2011-9-16 下午04:34:37
	 */
	public class DragComponent extends SpriteVisualElement {
		private static var _instance:DragComponent;

		private var _isDrag:Boolean = false;

		private var _resource:MapResource;

		public function DragComponent(enforce:SingletonEnforce) {
			if (enforce == null) {
				throw new Error("DragComponent can not be instance");
			}
		}

		public static function getInstance():DragComponent {
			if (_instance == null) {
				_instance = new DragComponent(new SingletonEnforce());
			}
			return _instance;
		}

		public function start(res:MapResource):void {
			if (res == null || res == _resource) {
				return;
			}
			
			while (numChildren > 0) {
				removeChildAt(0);
			}
			_resource = res;
			width = res.width;
			height = res.height;
			addChild(res);
			_isDrag = true;
			FlexGlobals.topLevelApplication.popLayer.addElement(this);
			this.x = stage.mouseX;
			this.y = stage.mouseY;
			startDrag(false);
			stage.addEventListener(MouseEvent.MOUSE_UP, stop);
		}

		private function stop(e:MouseEvent):void {
			stage.removeEventListener(MouseEvent.MOUSE_UP, stop);
			if (FlexGlobals.topLevelApplication.popLayer.contains(this)) {
				FlexGlobals.topLevelApplication.popLayer.removeElement(this);
				stopDrag();
				_isDrag = false;
				_resource = null;
			}
		}

		public function get isDrag():Boolean {
			return _isDrag;
		}

		public function get resource():MapResource {
			return _resource;
		}
	}
}

class SingletonEnforce {

}